package cn.com.open.itembank.service.impl;

import cn.com.open.itembank.common.CommonFunction;
import cn.com.open.itembank.common.Function;
import cn.com.open.itembank.common.GlobalConst;
import cn.com.open.itembank.common.enums.*;
import cn.com.open.itembank.dto.*;
import cn.com.open.itembank.entity.CourseItemBank;
import cn.com.open.itembank.entity.QuestionCategory;
import cn.com.open.itembank.entity.QuestionType;
import cn.com.open.itembank.exception.PoiException;
import cn.com.open.itembank.logic.importfilereader.FileReader;
import cn.com.open.itembank.logic.importfilereader.FileReaderFactory;
import cn.com.open.itembank.logic.importfilereader.WordFileReader;
import cn.com.open.itembank.logic.questiontype.QuestionTypeBase;
import cn.com.open.itembank.logic.questiontype.QuestionTypeFactory;
import cn.com.open.itembank.mapper.QuestionReadMapper;
import cn.com.open.itembank.service.ImportService;
import cn.com.open.itembank.service.ItemBankRemoteService;
import cn.com.open.itembank.service.ItemService;
import cn.com.open.itembank.service.QuestionCategoryRemoteService;
import cn.com.open.itembank.util.FileUtils;
import cn.com.open.itembank.util.HttpRequestUtils;
import cn.com.open.itembank.utils.DateUtil;
import cn.com.open.itembank.utils.JsonUtil;
import cn.com.open.itembank.utils.StringUtil;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * The type Import service.
 */
@Service("importService")
public class ImportServiceImpl implements ImportService {

    private static org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger(ItemServiceImpl.class);

    @Value("${app.resource.api.url}")
    private String resourceApiUrl;
    @Value("${app.image.save.type}")
    private int imageSaveType;

    @Autowired
    private QuestionReadMapper readMapper;
    @Autowired
    private ItemBankRemoteService itemBankService;
    @Autowired
    private ItemService itemService;
    @Autowired
    private QuestionCategoryRemoteService questionCategoryService;

    private static String itembankIdNotExist = "题库不存在";
    private static String noPermission = "无权限";

    //region 试题导入

    /**
     * 试题导入
     *
     * @param itemBankId     题库id
     * @param importQuestion importQuestion
     * @return
     * @throws Exception
     */
    @Override
    public ReturnModelForTestPaper importQuestion(String itemBankId, ImportParameter importQuestion) throws PoiException {

        return importLogic(importQuestion);
    }
    //endregion

    //region 输入参数检查

    /**
     * 输入参数检查.
     *
     * @param importParameter the input model
     * @return the return model
     */
    private ReturnModel checkParameter(ImportParameter importParameter) {
        ReturnModel model = new ReturnModel();

        if (StringUtils.isEmpty(importParameter.getItemBankId()) || StringUtils.isEmpty(importParameter.getResourceId())) {
            model.setCode(GlobalConst.INCOMPLETE_DATA);
            model.setMessage("参数不完整");
            return model;
        }

        //获取题库信息
        CourseItemBank courseItemBank = itemBankService.getCourseItemBankInfo(importParameter.getItemBankId());

        //校检ItemBankId
        if (courseItemBank == null) {
            model.setCode(GlobalConst.ID_NOT_EXIST);
            model.setMessage(itembankIdNotExist);
            return model;
        }

        //校检AppKey
        if (!itemBankService.hasPermission(importParameter.getItemBankId(), importParameter.getAppKey())) {
            model.setCode(GlobalConst.NO_PERMISSION);
            model.setMessage(noPermission);
            return model;
        }

        if (importParameter.getSourceType() == SourceType.TESTPAPER && StringUtils.isEmpty(importParameter.getPaperTitle())) {
            model.setCode(GlobalConst.PAPER_NAME_EMPTY);
            model.setMessage("试卷名称不能为空");
            return model;
        }

        model.setData(courseItemBank);
        model.setCode(GlobalConst.SUCCESS);
        return model;
    }
    //endregion

    //region 根据资源id获取资源文件路径

    /**
     * 根据资源id获取资源文件路径.(需要修改成为根据资源id通过资源服务获取文件并且下载到本地)
     *
     * @param resourceId the resource id
     * @return the upload file path
     */
    private String getUploadFilePath(String resourceId, String appkey, String appSecret) throws IOException {

        String urlString = CommonFunction.getPathByResources(resourceApiUrl, appkey, appSecret, resourceId, ResourceFileType.FILE);

        //获取路径中的文件后缀名下标
        int i = urlString.lastIndexOf(".");
        int j = urlString.lastIndexOf("?");

        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");

        //下载文件赋名字（时间戳）
        String fileName = String.format("%s%s", formatter.format(new Date()), urlString.substring(i, j));

        //根据地址下载文件
        String savePath = download(urlString, fileName);

        //删除给定文件夹下的最后编辑时间和当前时间差大于1天的历史文件
        FileUtils.deleteOldFiles(new File(savePath));
        //返回路径
        return savePath;
    }
    //endregion

    //region  根据地址下载文件

    /**
     * 根据地址下载文件
     *
     * @param urlString
     */
    private String download(String urlString, String fileName) throws IOException {
        //文件保存的相对路径
        String savePath = String.format("%s%s%s", System.getProperty("user.dir"), File.separator, "download");
        //创建连接
        URL url = new URL(urlString);
        //打开连接
        URLConnection con = url.openConnection();
        //输入流
        InputStream is = con.getInputStream();

        //1K的数据缓冲
        byte[] bs = new byte[1024];
        //读取到的数据长度
        int len;
        //输出的文件流
        File sf = new File(savePath);
        if (!sf.exists()) {
            sf.mkdirs();
        }
        String fileWritePath = String.format("%s%s%s", sf.getPath(), File.separator, fileName);
        try (OutputStream os = new FileOutputStream(fileWritePath)) {
            //开始读取
            while ((len = is.read(bs)) != -1) {
                os.write(bs, 0, len);
            }
            //完毕，关闭所有链接
            os.close();
        }
        //关流
        is.close();
        return fileWritePath;
    }
    //endregion

    //region 导入逻辑

    /**
     * 导入逻辑.
     *
     * @param importParameter the input model
     * @return the return model
     * @throws PoiException the poi exception
     */
    @Override
    public ReturnModelForTestPaper importLogic(ImportParameter importParameter) throws PoiException {
        //检查导入对象
        ReturnModel model = checkParameter(importParameter);
        ReturnModelForTestPaper newModel = new ReturnModelForTestPaper();

        if (model.getCode() != GlobalConst.SUCCESS) {
            newModel.setCode(model.getCode());
            newModel.setMessage(model.getMessage());
            return newModel;
        }
        //根据资源id获取到文件地址并下载返回一个文件保存的路径
        String fileSavePath = null;
        try {
            fileSavePath = getUploadFilePath(importParameter.getResourceId(), importParameter.getAppKey(), importParameter.getAppSecret());
        } catch (Exception e) {
            throw new PoiException(e.getMessage());
        }
        //根据导入文件类型创建对象，读取数据
        FileReader reader = FileReaderFactory.getInstance(Function.getExtName(fileSavePath),
                importParameter.getAppKey(), importParameter.getAppSecret(), resourceApiUrl, imageSaveType);
        if (reader == null) {
            newModel.setCode(GlobalConst.NOT_SUPPORT);
            newModel.setMessage("文件类型不支持");
            return newModel;
        }

        //读取数据
        List<QuestionImportModel> list = reader.getDataList(fileSavePath,Function.getExtName(fileSavePath));
        if (list.isEmpty()) {
            newModel.setCode(GlobalConst.FILE_FORMAT_ERROR);
            newModel.setMessage("文档读取失败");
            return newModel;
        }

        importParameter.setImportType(reader.getImportType());
        ReturnModelForTestPaper nModel = importUtility(importParameter,list,model);
        return nModel;
    }

    /**
     * 纯文本导入
     * @param importParameter the input model
     * @return
     * @throws PoiException
     */
    @Override
    public ReturnModelForTestPaper importTextLogic(ImportParameter importParameter) throws PoiException {
        String content = importParameter.getTextContent();

        //检查导入对象
        ReturnModel model = checkParameter(importParameter);
        ReturnModelForTestPaper newModel = new ReturnModelForTestPaper();

        List<QuestionImportModel> list = new WordFileReader().fillData(content);
        if (list.isEmpty()) {
            newModel.setCode(GlobalConst.FILE_FORMAT_ERROR);
            newModel.setMessage("文档读取失败");
            return newModel;
        }

        importParameter.setImportType(ImportType.TEXT);

        ReturnModelForTestPaper nModel = importUtility(importParameter,list,model);

        return nModel;
    }

    /**
     *
     * @param importParameter
     * @param list
     * @param model
     * @return
     * @throws PoiException
     */
    private ReturnModelForTestPaper importUtility(ImportParameter importParameter,List<QuestionImportModel> list,ReturnModel model) throws PoiException {
        ReturnModelForTestPaper newModel = new ReturnModelForTestPaper();
        //得到课程信息
        CourseItemBank courseItemBank = (CourseItemBank) model.getData();
        importParameter.setOrganizationId(courseItemBank.getCreateOrgID());
        importParameter.setSource(courseItemBank.getSource());

        //检查并形成试题模型
        ReturnModel returnModel = checkAndMakeQuestion(courseItemBank, importParameter, list);

        if (returnModel.getCode() != GlobalConst.SUCCESS) {
            //抛出错误文件
            String fileName = exportErrorFile(list);
            newModel.setCode(GlobalConst.DATA_FORMAT_ERROR);
            newModel.setMessage(fileName);
            return newModel;
        }

        //保存入库
        List<QuestionModel> successList = (List<QuestionModel>) returnModel.getData();

        for (QuestionModel item : successList) {
            //因为试卷导入时候重题被标记在i1了
            if (StringUtils.isEmpty(item.getI1())) {
                ReturnModel itemReturn = itemService.addQuestion(item, importParameter.getSource(),
                        importParameter.getSourceType().getIndex(), InputType.FILEINPUT.getIndex(),
                        importParameter.getImportType().getIndex(), importParameter.getAppKey());
                if (itemReturn.getCode() == GlobalConst.SUCCESS) {
                    item.setI1(itemReturn.getData().toString());
                }
            }
        }

        if (importParameter.getSourceType() == SourceType.TESTPAPER) {
            TestPaperModel map = getItemsForPaper(successList);
            newModel.setData(map);
        }
        newModel.setCode(GlobalConst.SUCCESS);
        newModel.setMessage("导入成功");
        return newModel;


    }
    //endregion

    //region 格式化试卷用试题列表

    /**
     * 格式化试卷用试题列表.
     *
     * @param items the items
     * @return the items for paper
     */
    private TestPaperModel getItemsForPaper(List<QuestionModel> items) {
        TestPaperModel paper = new TestPaperModel();
        PaperPart part = new PaperPart();

        for (QuestionModel item : items) {
            boolean isExistSection = false;

            PaperItem paperItem = new PaperItem();
            //主观题默认人工评阅，客观题自动评阅,i32的客观题0，主观题1
            paperItem.setSubjective(item.getI32() == 1);
            //得到每个试题的id和分数
            paperItem.setScore(item.getI9());
            paperItem.setItemId(item.getI1());
            paperItem.setQuestionTypeId(item.getI3());

            for (PaperSection section : part.getSections()) {
                if (section.getIdentifier().equalsIgnoreCase(item.getI30())) {
                    section.getItems().add(paperItem);
                    isExistSection = true;
                    break;
                }
            }

            if (!isExistSection) {
                //大题信息不存在
                PaperSection section = new PaperSection();
                section.setTitle(item.getI21());
                section.setIdentifier(item.getI30());
                section.setShuf(false);
                section.getItems().add(paperItem);

                part.getSections().add(section);
            }
        }

        paper.getParts().add(part);

        return paper;
    }
    //endregion

    //region 检查并形成试题模型

    /**
     * 检查并形成试题模型.
     *
     * @param courseItemBank  the course item bank
     * @param importParameter the input model
     * @param itemList        the item list
     * @return the string
     */
    private ReturnModel checkAndMakeQuestion(CourseItemBank courseItemBank, ImportParameter importParameter, List<QuestionImportModel> itemList) {
        ReturnModel returnModel = new ReturnModel();

        boolean checkPass = true;

        //获取课程的题型列表
        List<QuestionType> questionTypeList = itemBankService.getListByItemBankId(courseItemBank.getItemBankID());
        //获取所有可用类别列表
        List<QuestionCategory> categories = questionCategoryService.getEnabledList("");

        //获取外部课程的资源系统中的章节信息
        List<Map<String, String>> outerChapterList = null;
        if (importParameter.getSource() == Source.OUTER.getIndex() && StringUtils.isEmpty(importParameter.getChapterId())) {
            outerChapterList = getOuterChapter(courseItemBank.getCourseID());
        }

        //存库模型集合
        List<QuestionModel> successList = new ArrayList<>();

        //校验通用模型，如果校验成功将其转换为存库模型
        for (QuestionImportModel item : itemList) {
            QuestionModel model = makeQuestionModel(item, questionTypeList, categories, outerChapterList, importParameter);

            if (model == null) {
                checkPass = false;
                continue;
            }

            //重题检查
            List<String> exists = checkExistQuestion(model);

            if (exists == null || exists.isEmpty()) {
                successList.add(model);
            } else {
                if (importParameter.getSourceType() == SourceType.QUESTION) {
                    //试题导入不允许存在重复试题
                    item.setErrorInfo(String.format("存在重复试题，数量为：%s", exists.size()));
                    checkPass = false;
                }

                if (importParameter.getSourceType() == SourceType.TESTPAPER) {
                    //如果试卷导入存在重复试题，则默认第1道重复试题作为导入试卷的试题，将id记录到i1中
                    model.setI1(exists.get(0));
                    successList.add(model);
                }
            }
        }

        if (checkPass) {
            returnModel.setCode(GlobalConst.SUCCESS);
            returnModel.setData(successList);
        } else {
            returnModel.setCode(GlobalConst.DATA_FORMAT_ERROR);
        }

        return returnModel;
    }

    /**
     * 创建试题存库模型.
     *
     * @param item             the item
     * @param questionTypeList the question type list
     * @param categories       the categories
     * @param outerChapterList the outer chapter list
     * @param importParameter  the import parameter
     * @return the question model
     */
    private QuestionModel makeQuestionModel(QuestionImportModel item, List<QuestionType> questionTypeList, List<QuestionCategory> categories,
                                            List<Map<String, String>> outerChapterList, ImportParameter importParameter) {


        if (!StringUtil.isEmpty(item.getErrorInfo())) {
            return null;
        }

        //得到模型中的试题类型名称
        String questionTypeName = item.getQuestionTypeName();
        //得到试题类型模型
        QuestionType qtype = getQuestionTypeByName(questionTypeName, questionTypeList);

        if (qtype == null) {
            item.setErrorInfo("未找到题型:" + questionTypeName);
            item.setQuestionType(questionTypeName);

            return null;
        }

        //更新模型的试题类型名称为试题内部题型id
        item.setQuestionType(qtype.getQuestionTypeID());
        //根据不同题型初始化各种题型转换模型
        QuestionTypeFactory factory = new QuestionTypeFactory(item);
        QuestionTypeBase questionTypeBase = factory.getInstance(qtype.getQuestionInnerTypeID());

        if (questionTypeBase == null) {
            item.setErrorInfo("未找到题型解析:" + questionTypeName);
            item.setQuestionType(questionTypeName);

            return null;
        }

        questionTypeBase.setImportParameter(importParameter);
        questionTypeBase.setQuestionTypes(questionTypeList);
        questionTypeBase.setQuestionType(qtype);
        questionTypeBase.setCategories(categories);
        questionTypeBase.setOuterChapterList(outerChapterList);

        //数据校验
        boolean flag = questionTypeBase.checkSummary();
        //校验失败加入失败列表
        if (!flag) {
            return null;
        }
        //校验成功后获取转换后的试题模型
        return questionTypeBase.getSaveModel();
    }
    //endregion

    //region 检查重复试题

    /**
     * 检查重复试题.
     *
     * @param model the model
     * @return the list
     */
    private List<String> checkExistQuestion(QuestionModel model) {
        Map<String, Object> checkMap = getExistQuestionCheckModel(model);

        String json = getCheckModelJson(checkMap);

        return readMapper.getSameQuestion(model.getI4(), json);
    }
    //endregion

    //region 将重复试题检查map转换成为查询用的json字符串

    /**
     * 将重复试题检查map转换成为查询用的json字符串.
     *
     * @param checkMap the check map
     * @return the check model json
     */
    private String getCheckModelJson(Map<String, Object> checkMap) {
        return JsonUtil.getJson(checkMap).replace("\"", "\\\"")
                .replace("'", "''")
                .replace("{", "")
                .replace("}", "");
    }
    //endregion

    //region 获取重复试题检查map

    /**
     * 获取重复试题检查map.
     *
     * @param model the model
     * @return the exist question check model
     */
    private Map<String, Object> getExistQuestionCheckModel(QuestionModel model) {
        Map<String, Object> map = new LinkedHashMap<>();

        map.put("I2", model.getI2());
        map.put("I3", model.getI3());
        map.put("I4", model.getI4());
        map.put("I5", model.getI5());
        map.put("I6", model.getI6());
        map.put("I7", model.getI7());

        return map;
    }
    //endregion

    //region 根据题型名称查询得到题型模型

    /**
     * 根据题型名称查询得到题型模型.
     *
     * @param name             the name
     * @param questionTypeList the question type list
     * @return the question type by name
     */
    private QuestionType getQuestionTypeByName(String name, List<QuestionType> questionTypeList) {
        String typeName = name;

        if ("完型填空题".equalsIgnoreCase(name) || "阅读理解题".equalsIgnoreCase(name)) {
            typeName = name.replace("题", "");
        }

        for (QuestionType type : questionTypeList) {
            if (type.getQuestionTypeName().equalsIgnoreCase(typeName)) {
                return type;
            }
        }

        return null;
    }
    //endregion

    //region 获取外部章节信息

    /**
     * 获取外部章节信息.
     *
     * @param courseId the course id
     * @return the external chapter
     */
    private List<Map<String, String>> getOuterChapter(String courseId) {
        try {
            String url = "courses/" + courseId + "/catalogTree";
            Map<String, String> headers = new HashMap<>();
            headers.put("appkey", "c655762fdf5979cb382c94061d6ddebb");
            headers.put("appsecret", "a92831a56f957a98e2ebe10caff37f86");

            String result = HttpRequestUtils.doGet(resourceApiUrl, url, null, headers);
            ResourceResponse resource = ResourceResponse.init(result);

            if (!resource.isSuccess()) {
                return new ArrayList<>();
            }

            return (List<Map<String, String>>) resource.getPayload();

        } catch (Exception ex) {
            logger.error(ex.getMessage());
        }

        return new ArrayList<>();
    }
    //endregion


    //region 获得导出的文件名称路径

    /**
     * 获得导出的word文件名称路径.
     *
     * @return the file
     */
    private String getExcelFilePath() {
        //导出文件名称
        String fileName = String.format("%s.xls", DateUtil.getCurrentTimeToLongString());

        return CommonFunction.getFileFullPath("export", fileName);
    }
    //endregion

    //region 导出excel错误输出文档，并且返回路径

    /**
     * 导出excel错误输出文档，并且返回路径.
     *
     * @param itemList the item list
     * @return the string
     * @throws Exception the exception
     */
    private String exportErrorFile(List<QuestionImportModel> itemList) throws PoiException {
        //get word file name
        String fileName = getExcelFilePath();
        //make word file
        printExcel(itemList, fileName);

        return fileName;
    }
    //endregion

    //region 得到输出的题干字符串

    /**
     * 得到输出的题干字符串.
     *
     * @param model the model
     * @return the sub content
     */
    private String getSubContent(QuestionImportModel model) {
        List<String> content = new ArrayList<>();
        boolean hasSeparator = false;

        for (QuestionImportModel sub : model.getSubItems()) {
            //如果子试题的题干中含有分隔符，则标记
            if (sub.getPrompt().indexOf(CommonFunction.SEPARATOR) >= 0) {
                hasSeparator = true;
            }
            content.add(sub.getPrompt());
        }

        //如果子试题题干没有标准分隔符则使用标准分隔符，否则使用子试题分隔符
        String separatorOpt = hasSeparator ? CommonFunction.SUB_ITEM_SEPARATOR : CommonFunction.SEPARATOR;

        return String.join(separatorOpt, content);
    }
    //endregion

    //region 得到输出的选项字符串

    /**
     * 得到输出的选项字符串.
     *
     * @param model the model
     * @return the choice
     */
    private String getChoice(QuestionImportModel model) {
        List<String> content = new ArrayList<>();
        boolean hasChild = !model.getSubItems().isEmpty();

        if (!hasChild) {
            return CommonFunction.getEachList(model.getChoices());
        }

        for (QuestionImportModel sub : model.getSubItems()) {
            content.add(CommonFunction.getEachList(sub.getChoices()));
        }

        return String.join(CommonFunction.SUB_ITEM_SEPARATOR, content);
    }
    //endregion

    //region 得到输出的答案字符串

    /**
     * 得到输出的答案字符串.
     *
     * @param model the model
     * @return the answer
     */
    private String getAnswer(QuestionImportModel model) {
        List<String> content = new ArrayList<>();
        boolean hasChild = !model.getSubItems().isEmpty();
        boolean hasSeparator = false;

        if (!hasChild) {
            return CommonFunction.getEachList(model.getAnswer());
        }

        for (QuestionImportModel sub : model.getSubItems()) {
            String str = CommonFunction.getEachList(sub.getAnswer());
            //如果子试题的题干中含有分隔符，则标记
            if (str.indexOf(CommonFunction.SEPARATOR) >= 0) {
                hasSeparator = true;
            }
            content.add(str);
        }

        //如果子试题题干没有标准分隔符则使用标准分隔符，否则使用子试题分隔符
        String separatorOpt = hasSeparator ? CommonFunction.SUB_ITEM_SEPARATOR : CommonFunction.SEPARATOR;
        return String.join(separatorOpt, content);
    }
    //endregion

    //region 得到输出的分数字符串

    /**
     * 得到输出的分数字符串.
     *
     * @param model the model
     * @return the score
     */
    private String getScore(QuestionImportModel model) {
        List<String> content = new ArrayList<>();
        Set<String> scoreNotSame = new HashSet<>();
        boolean hasChild = !model.getSubItems().isEmpty();

        if (!hasChild) {
            return model.getScore();
        }

        for (QuestionImportModel sub : model.getSubItems()) {
            content.add(sub.getScore());
            scoreNotSame.add(sub.getScore());
        }

        if (scoreNotSame.size() == 1) {
            return content.get(0);
        }

        return String.join(CommonFunction.SEPARATOR, content);
    }
    //endregion

    //region 得到输出的解析字符串

    /**
     * 得到输出的解析字符串.
     *
     * @param model the model
     * @return the Analysis
     */
    private String getAnalysis(QuestionImportModel model) {
        List<String> content = new ArrayList<>();
        List<String> totalAnalysis = new ArrayList<>();
        boolean hasChild = !model.getSubItems().isEmpty();

        if (!hasChild) {
            return model.getQuestionAnalysis();
        }

        for (QuestionImportModel sub : model.getSubItems()) {
            if (!StringUtils.isEmpty(sub.getQuestionAnalysis())) {
                content.add(sub.getQuestionAnalysis());
            }
        }

        if (content.isEmpty()) {
            return model.getQuestionAnalysis();
        }

        totalAnalysis.add(model.getQuestionAnalysis());
        totalAnalysis.add(String.join(CommonFunction.SEPARATOR, content));

        return String.join(CommonFunction.SUB_ITEM_SEPARATOR, totalAnalysis);
    }
    //endregion

    //region 得到输出数据

    /**
     * 得到输出数据.
     *
     * @param itemList the item list
     * @return the excel data
     */
    private List<List<String>> getExcelData(List<QuestionImportModel> itemList) {
        List<List<String>> list = new ArrayList<>();

        for (QuestionImportModel model : itemList) {
            List<String> data = new ArrayList<>();

            data.add(model.getQuestionTypeName());
            data.add(model.getQuestionCategoryName());
            data.add(model.getSaveDiffWord());
            data.add(model.getPrompt());
            data.add(getSubContent(model));
            data.add(getChoice(model));
            data.add(getAnswer(model));
            data.add(getScore(model));
            data.add(getAnalysis(model));
            data.add(model.getChapter());
            data.add("");
            data.add(model.getErrorInfo());

            list.add(data);
        }

        return list;
    }
    //endregion

    //region 将数据输出到excel

    /**
     * 将数据输出到excel.
     *
     * @param itemList the item list
     * @param fileName the file name
     * @throws Exception the exception
     */
    private void printExcel(List<QuestionImportModel> itemList, String fileName) throws PoiException {

        try (HSSFWorkbook workbook = new HSSFWorkbook()) {
            //新建工作表
            HSSFSheet sheet = workbook.createSheet("试题内容");

            //创建行,0表示第一行
            HSSFRow row = sheet.createRow(0);
            String[] titles = {"题型名称", "试题类别编码", "难度编码", "题目内容", "子题内容", "选项", "答案", "分数", "试题解析", "章节", "子题类型", "错误信息"};
            for (int i = 0; i < titles.length; i++) {
                HSSFCell cell = row.createCell(i);
                cell.setCellValue(titles[i]);
            }

            List<List<String>> data = getExcelData(itemList);

            for (int i = 0; i < data.size(); i++) {
                HSSFRow rowData = sheet.createRow(i + 1);

                for (int j = 0; j < data.get(i).size(); j++) {
                    HSSFCell cell = rowData.createCell(j);
                    cell.setCellValue(data.get(i).get(j));
                }
            }

            //创建输出流
            FileOutputStream out = new FileOutputStream(fileName);
            workbook.write(out);
            workbook.close();
        } catch (Exception e) {
            throw new PoiException(e.getMessage());
        }
    }
    //endregion

}